<!--
*@Author: zt
*@Description: 请假申请
*@Date: 2024-08-20
-->
<template>
  <u-dialog
    v-bind="$attrs"
    :title="title"
    :hideBtns="formDisabled ? ['submit'] : []"
    @submit="submit"
    @close="dialogClose"
  >
    <template v-slot:footerBefore>
      <template v-if="!formDisabled">
        <u-icon-button itype="save" @click="submit('up')">
          保存并上报
        </u-icon-button>
      </template>
      <template
        v-if="
          route.params.pType == '2' &&
          form['status'] == '2' &&
          isAudited == true
        "
      >
        <u-icon-button itype="approve" @click="auditAbout1('2')">
          批准
        </u-icon-button>
        <u-icon-button itype="close" @click="auditAbout1('3')">
          退回
        </u-icon-button>
      </template>
    </template>
    <a-layout class="f-h-100">
      <a-layout-content class="s-bg-white" style="overflow: auto">
        <u-flow-tab
          activeKey="1"
          :show="isValue(form.status)"
          :isAudit="form.status == 2"
          :isAuditPage="route.params.pType == '2'"
          :params="{ type: 'leave_apply', ...form }"
          v-bind="$attrs"
          ref="auditRef"
        >
          <a-tab-pane key="1" tab="基本信息">
            <a-space direction="vertical" class="f-w-100">
              <u-busi-card title="基本信息" :bordered="false">
                <u-form
                  :elements="formEls"
                  :model="form"
                  :gutter="0"
                  ref="formRef"
                ></u-form>
              </u-busi-card>
              <u-busi-card title="附件">
                <u-field-upload
                  v-model:value="fileData"
                  :disabled="formDisabled"
                  :fileParams="{
                    bucket: 'ADM_BIZ_TYPE_ATTENDANCE',
                    biztype: '2',
                  }"
                ></u-field-upload>
              </u-busi-card>
            </a-space>
          </a-tab-pane>
        </u-flow-tab>
      </a-layout-content>
    </a-layout>
  </u-dialog>
</template>

<script lang="ts" setup>
import {
  ref,
  reactive,
  computed,
  onMounted,
  h,
  useAttrs,
  watch,
  watchEffect,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useBaseStore, useLoginStore } from '@/store';
import { storeToRefs } from 'pinia';
import { _IFormEl, _IExtra } from '@/src/components/common/form/interface';
import { Cascader, FormInstance, FormItemProps } from 'ant-design-vue';
import { _IColumnProps } from '@/components/common/tableEdit/interface.ts';
import { _IAuditFlow } from '@/views/oa/personnel/checkinEdit/auditFlow/interface.ts';
import { urlFile } from '@/util/common';
import { alertC, messageC, isValue, nullC, numberC } from '@/util/common';
import { useAuditAbout, IAuditParams } from '@/hooks/useAudit';
import dayjs from 'dayjs';
import * as areaApi from '@/service/system/area';
import * as myCheckInApi from '@/service/personnel/myCheckIn/index';

const props = defineProps<{
  isAudited?: boolean;
}>();

const emits = defineEmits(['success']);
const attrs = useAttrs();
const fileData = ref([]);
const { userInfo } = storeToRefs(useLoginStore());
const { LEAVE_TYPE } = storeToRefs(useBaseStore());

const route = useRoute();

const title = computed(() => {
  const text = {
    1: '加班编辑',
    2: '请假编辑',
    3: '离驻地编辑',
  };
  return nullC(text[attrs.busiType]);
});

// 表单数据
const auditRef = ref<FormInstance>();
const formRef = ref<FormInstance>();
let form = ref<any>({
  applicantdate: dayjs().format('YYYY-MM-DD'),
  fkdeptname: userInfo.value['deptName'],
  fkdeptid: userInfo.value['deptId'],
  fkapplicant: userInfo.value['name'],
  fkapplicantid: userInfo.value['userId'],
  applicanttype: '',
  status: '1',
  leavedays: 0, // 请假天数
  leavecddays: '', // 离驻地天数
  // fkapplicant:userInfo.value['']
});
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '90px',
  colon: false,
};

let baseSelData = reactive<any>({
  fkareaidData: [],
});
const dateNoon = ref([
  {
    value: '1',
    label: '上午',
  },
  {
    value: '2',
    label: '下午',
  },
]);
let formDisabled = ref<any>(false);
const formEls: Array<_IFormEl> = computed(() => {
  return [
    {
      label: '申请部门',
      key: 'fkdeptname',
      col: { span: 8 },
      element: 'input',
      formItemProps: { ...formItemProps },
      componentProps: { disabled: true },
    },
    {
      label: '申请人',
      key: 'fkapplicant',
      col: { span: 8 },
      element: 'input',
      formItemProps: { ...formItemProps, required: true },
      componentProps: { disabled: true },
    },
    {
      label: '申请时间',
      key: 'applicantdate',
      col: { span: 8 },
      element: 'datepicker',
      formItemProps: { ...formItemProps, required: true },
      componentProps: { disabled: true },
    },
    {
      label: '开始时间',
      key: 'startdate',
      col: { span: attrs.busiType == '1' ? 8 : 4 },
      element: 'datepicker',
      hide: attrs.busiType != '1',
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        showTime: attrs.busiType == '1',
        valueFormat: 'YYYY-MM-DD HH:mm',
        format: 'YYYY-MM-DD HH:mm',
        disabled: formDisabled.value,
        // disabledDate: (current: Dayjs) => {
        //   if (current && form['endstart']) {
        //     return dayjs(form['endstart']).subtract(1, 'day').endOf('day') < current
        //   }
        // }
      },
    },
    {
      label: '开始时间',
      key: 'startdate',
      col: { span: attrs.busiType == '1' ? 8 : 4 },
      element: 'datepicker',
      hide: attrs.busiType == '1',
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        showTime: attrs.busiType == '1',
        valueFormat: 'YYYY-MM-DD HH:mm',
        disabled: formDisabled.value,
        // disabledDate: (current: Dayjs) => {
        //   if (current && form['endstart']) {
        //     return dayjs(form['endstart']).subtract(1, 'day').endOf('day') < current
        //   }
        // }
      },
    },
    {
      label: '',
      key: 'startdate_echo',
      col: { span: 4 },
      element: 'select',
      hide: attrs.busiType == '1',
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        options: computed(() => dateNoon.value),
        disabled: formDisabled.value,
      },
    },
    {
      label: '结束时间',
      key: 'endstart',
      col: { span: attrs.busiType == '1' ? 8 : 4 },
      element: 'datepicker',
      hide: attrs.busiType != '1',
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        showTime: attrs.busiType == '1',
        valueFormat: 'YYYY-MM-DD HH:mm',
        format: 'YYYY-MM-DD HH:mm',
        disabled: formDisabled.value,
        // disabledDate: (current: Dayjs) => {
        //   if (current && form['startdate']) {
        //     return dayjs(form['startdate']).subtract(1, 'day').endOf('day') > current
        //   }
        // }
      },
    },
    {
      label: '结束时间',
      key: 'endstart',
      col: { span: attrs.busiType == '1' ? 8 : 4 },
      element: 'datepicker',
      hide: attrs.busiType == '1',
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        showTime: attrs.busiType == '1',
        valueFormat: 'YYYY-MM-DD HH:mm',
        disabled: formDisabled.value,
        // disabledDate: (current: Dayjs) => {
        //   if (current && form['startdate']) {
        //     return dayjs(form['startdate']).subtract(1, 'day').endOf('day') > current
        //   }
        // }
      },
    },
    {
      label: '',
      key: 'endstart_echo',
      col: { span: 4 },
      element: 'select',
      hide: attrs.busiType == '1',
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        options: computed(() => dateNoon.value),
        disabled: formDisabled.value,
      },
    },
    {
      label: '加班时长',
      key: 'overtimes',
      col: { span: 8 },
      element: 'number',
      hide: attrs.busiType != '1',
      formItemProps: { ...formItemProps },
      componentProps: { disabled: true },
      disabled: formDisabled.value,
    },
    {
      label: '天数',
      key: 'leavedays',
      col: { span: 8 },
      element: 'number',
      hide: attrs.busiType != '2',
      formItemProps: { ...formItemProps },
      componentProps: { disabled: true },
      disabled: formDisabled.value,
    },
    {
      label: '天数',
      key: 'leavecddays',
      col: { span: 8 },
      element: 'number',
      hide: attrs.busiType != '3',
      formItemProps: { ...formItemProps },
      componentProps: { disabled: true },
      disabled: formDisabled.value,
    },
    {
      label: '请假类型',
      key: 'leavetype',
      col: { span: 8 },
      element: 'select',
      hide: attrs.busiType != '2',
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        options: computed(() => LEAVE_TYPE.value),
        disabled: formDisabled.value,
      },
    },
    {
      label: '前往地区',
      key: 'fkregionname',
      col: { span: 8 },
      element: 'treeselect',
      hide: attrs.busiType != '3',
      formItemProps: { ...formItemProps, required: true },
      componentProps: {
        treeData: computed(() => baseSelData.fkareaidData),
        fieldNames: { label: 'name', value: 'name' },
        showCheckedStrategy: Cascader.SHOW_CHILD,
        disabled: formDisabled.value,
      },
    },
    {
      label: '事由',
      key: 'reason',
      col: { span: 24 },
      element: 'textarea',
      formItemProps: { ...formItemProps, required: true },
      componentProps: { disabled: formDisabled.value },
    },
    // { label: '附件', key: 'file', col: { span: 24 }, element: 'file',
    //   formItemProps: { ...formItemProps, required: true }
    // },
  ];
});

//保存
const submit = (type?: string) => {
  fileData.value.map(e => {
    if (e['name']) {
      e['filename'] = e['name'];
    }
  });

  const time1 = dayjs(form.value['startdate']);
  const time2 = dayjs(form.value['endstart']);

  if (time2.isBefore(time1)) {
    messageC('开始时间要小于结束时间', 'warning');
    return;
  }
  form.value['appendixSaveVOList'] = fileData.value;

  formRef.value.form
    .validate()
    .then(async () => {
      const url = attrs.keyid ? 'update' : 'add';
      if (url == 'add') {
        form.value.status = '1';
      }
      const res = await myCheckInApi[url](form.value);
      if (res.code == 0) {
        if (url == 'add') {
          form.value.keyid = res.data.keyid;
          form.value.status = res.data.status;
        }
        if (type == 'up') {
          await auditAbout1('1');
          await emits('success');
          dialogClose();
        } else {
          messageC(res.msg, 'success');
          emits('success');
          dialogClose();
        }
      } else {
        messageC(res.msg, 'warning');
      }
    })
    .catch(() => {
      messageC('请先将表单填写完毕！');
    });
};

// 弹窗关闭
const dialogClose = () => {
  form.value = {};
  fileData.value = [];
  form.value.applicantdate = dayjs().format('YYYY-MM-DD');
  form.value.fkdeptname = userInfo.value['deptName'];
  form.value.fkdeptid = userInfo.value['deptId'];
  form.value.fkapplicant = userInfo.value['name'];
  form.value.fkapplicantid = userInfo.value['userId'];
  if (formRef.value) {
    formRef.value.form.resetFields();
  }
};

// 获取地区
const getFkareaid = async () => {
  try {
    const data = await areaApi.validTree(userInfo.value['unitId']);

    if (data.code == 0) {
      baseSelData.fkareaidData = data.data;

      //地区返回做处理   --留痕——zt
      if (
        baseSelData.fkareaidData &&
        baseSelData.fkareaidData[0].children.length > 0
      ) {
        if (
          baseSelData.fkareaidData[0].children[0].keyid == '14' &&
          baseSelData.fkareaidData[0].children[0].name == '自贡市内'
        ) {
          baseSelData.fkareaidData[0].children[0].name = '自贡市';
          baseSelData.fkareaidData[0].children[0].children = [];
        }
        if (
          baseSelData.fkareaidData[baseSelData.fkareaidData.length - 1].name ==
          '成都2'
        ) {
          baseSelData.fkareaidData = baseSelData.fkareaidData.slice(0, -1);
        }
      }
    }
  } catch (error) {}
};

//回显
const getEcho = async keyid => {
  const res = await myCheckInApi.admTAttendance(keyid);
  if (res.code == 0) {
    form.value = res.data || {};

    fileData.value = res.data.appendix;

    if (attrs.busiType == '3' || attrs.busiType == '2') {
      form.value['startdate'] = dayjs(form.value['startdate']).format(
        'YYYY-MM-DD HH:mm'
      );
      form.value['endstart'] = dayjs(form.value['endstart']).format(
        'YYYY-MM-DD HH:mm'
      );

      const startdateHour = numberC(
        dayjs(form.value['startdate']).format('HH')
      );
      form.value['startdate_echo'] = startdateHour <= 12 ? '1' : '2';

      const endstartHour = numberC(dayjs(form.value['endstart']).format('HH'));
      form.value['endstart_echo'] = endstartHour > 12 ? '2' : '1';
    }
  }
};

// 上报、审核、退回
const auditAbout1 = async (type: string | number) => {
  form.value['appendixSaveVOList'] = fileData.value;
  const auditParams: IAuditParams = {
    type: 'leave_apply',
    selDatas: [form.value],
    confirm: false,
    isDialog: false,
  };

  try {
    const res = await useAuditAbout(type, auditParams, auditRef);
    if (res) {
      messageC(res.msg, 'success');
      emits('success');
      dialogClose();
    }
  } catch (error) {}
};

watchEffect(() => {
  // 请假、离驻地
  if (attrs.busiType == 2 || attrs.busiType == 3) {
    const { endstart, startdate, startdate_echo, endstart_echo } = form.value;
    let startdateS = `${startdate || ''}`.split(' ')[0];
    let endstartS = `${endstart || ''}`.split(' ')[0];

    let startdateT = `${startdateS}${
      startdate_echo == 2 ? ' 12:00' : ' 00:00'
    }`;
    let endstartT = `${endstartS}${endstart_echo == 1 ? ' 12:00' : ' 24:00'}`;

    let hours = dayjs(endstartT).diff(startdateT, 'hour');
    let halfDay = hours % 12;
    if (attrs.busiType == 2) {
      form.value.leavedays = (hours - halfDay) / 24 + (halfDay == 0 ? 0 : 0.5);
    } else {
      form.value.leavecddays =
        (hours - halfDay) / 24 + (halfDay == 0 ? 0 : 0.5);
    }

    // 设置时分
    if (form.value.startdate != startdateT && form.value.startdate) {
      form.value.startdate = startdateT;
    }

    let fzEndStartText = `${endstartS}${
      endstart_echo == 1 ? ' 12:00' : ' 23:59'
    }`;
    if (form.value.endstart != fzEndStartText && form.value.endstart) {
      form.value.endstart = fzEndStartText;
    }
  }
  // 加班
  else if (attrs.busiType == 1) {
    const { endstart, startdate } = form.value;
    if (endstart && endstart) {
      let minutes = dayjs(endstart).diff(startdate, 'minute');
      let hours = minutes / 60;
      form.value.overtimes = `${hours}`.includes('.')
        ? hours.toFixed(1)
        : hours;
    } else {
      form.value.overtimes = 0;
    }
  }
});

watch(
  () => attrs.open,
  async (nval, oval) => {
    if (nval == true) {
      if (attrs.busiType) {
        form.value['applicanttype'] = attrs.busiType;
      }
      if (attrs.keyid) {
        await getEcho(attrs.keyid);
      }

      await getFkareaid();
      formDisabled.value = attrs.formDisabled;
    } else if (nval == false) {
      form.value['leavecddays'] = 0;
      form.value['leavedays'] = 0;
      form.value['overtimes'] = 0;
      form.value['endstart'] = '';
      form.value['startdate'] = '';
      form.value['reason'] = '';
      fileData.value = [];
    }
  }
);
</script>

<style lang="scss"></style>
